<template>
  <el-select
    ref="select"
    v-model="selectValue"
    v-load-more="onNextPage"
    v-bind="$attrs"
    remote
    :multiple="multiple"
    :remote-method="onRemoteMethod"
    v-on="$listeners"
    @change="onChange"
    @focus="onFocus"
    @clear="onClear"
  >
    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
  </el-select>
</template>

<script>
import { isEmpty } from 'element-ui/src/utils/util'
import select from './mixins/select'
export default {
  name: 'RemoteSelect',
  mixins: [select],
  props: {
    // 远程数据,只能传入promise方法
    remoteData: {
      type: Function,
      required: true
    },
    // 回显远程数据,只能传入promise方法
    remoteDataEcho: {
      type: Function,
      default: undefined
    },
    // 数据格式
    dataFormat: {
      type: Object,
      default: function() {
        return { value: 'value', label: 'label' }
      }
    }
  },
  methods: {
    loadData(replace) {
      this.remoteData(this.query).then(res => {
        if (replace) {
          this.options = []
        }
        this.total = res.total
        res.rows.forEach(item => {
          if (this.checkDataNotExist(item[this.dataFormat.value])) {
            this.options.push({
              value: item[this.dataFormat.value],
              label: item[this.dataFormat.label]
            })
          }
        })
      })
    },
    echoLoadData() {
      if (!isEmpty(this.value) && this.checkDataNotExist(this.value)) {
        this.remoteDataEcho(this.value).then(res => {
          if (this.checkDataNotExist(res.data[this.dataFormat.value])) {
            this.options.push({
              value: res.data[this.dataFormat.value],
              label: res.data[this.dataFormat.label]
            })
          }
          this.selectValue = this.value
        })
      } else {
        this.selectValue = this.value
      }
    }
  }
}
</script>

<style scoped>

</style>
